package com.dianrui.firemenmonitor.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.dianrui.firemenmonitor.Constant;
import com.dianrui.firemenmonitor.R;
import com.dianrui.firemenmonitor.adapter.AttendaceListAdapter;
import com.dianrui.firemenmonitor.adapter.FieldListAdapter;
import com.dianrui.firemenmonitor.adapter.FieldListAdapters;
import com.dianrui.firemenmonitor.bean.AttendaceBean;
import com.dianrui.firemenmonitor.bean.FieldBean;
import com.dianrui.firemenmonitor.util.OkHttpUtils;
import com.dianrui.firemenmonitor.util.StringUtils;
import com.dianrui.firemenmonitor.util.ToastUtil;
import com.dianrui.firemenmonitor.util.Url;
import com.dianrui.firemenmonitor.view.InnerListview;
import com.google.gson.JsonObject;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 考勤/外勤打卡界面
 */
public class AttendaceActivity extends BaseActivity {
    private ProgressDialog pd;
    private static final int msgKey = 1;
    private List<AttendaceBean> attendaceBeanList = new ArrayList<>();
    private List<FieldBean> fieldBeanList = new ArrayList<>();
    private List<FieldBean> fieldChooseDateBeanList = new ArrayList<>();
    private String chooseAttendancetype="1";
    private AttendaceListAdapter attendaceListAdapter;
    private FieldListAdapter fieldListAdapter;
    private FieldListAdapters fieldListAdapters;
    private String todaysdate;
    private boolean isFirstLoc = true;
    public LocationClient mLocationClient = null;
    private Context context;
    private double latitude;
    private int count;
    private int flieldcount;
    private double longitude;

    @BindView(R.id.attendance_img)
    ImageView attendanceImg;
    @BindView(R.id.field_img)
    ImageView fieldImg;
    @BindView(R.id.calendat_pulldown)
    ImageView calendatPulldown;
    @BindView(R.id.calendat_pullup)
    ImageView calendatPullup;
    @BindView(R.id.attendance_layout)
    FrameLayout attendanceLayout;
    @BindView(R.id.current_time1)
    TextView currentTime1;
    @BindView(R.id.attendence_txt)
    TextView attendenceTxt;
    @BindView(R.id.field_txt1)
    TextView fieldTxt1;
    @BindView(R.id.field_layout)
    FrameLayout fieldLayout;
    @BindView(R.id.listview)
    InnerListview listview;
    @BindView(R.id.calendarView)
    MaterialCalendarView calendarView;
    @BindView(R.id.current_date)
    TextView currentDate;
    @BindView(R.id.current_time)
    TextView currentTime;
    @BindView(R.id.current_address)
    TextView currentAddress;
    @BindView(R.id.attendace_top_btn)
    Button attendaceTopBtn;
    @BindView(R.id.fieldwork_top_btn)
    Button fieldworkTopBtn;
    @BindView(R.id.current_address_layout)
    LinearLayout currentAddressLayout;


    @Override
    public int getContentViewId() {
        return R.layout.activity_attendance;
    }

    @Override
    public void initView() {
        customInit(R.color.blue_518bfa);
        context = this;
        pd=new ProgressDialog(this);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        currentDate.setText(simpleDateFormat.format(date));

        new TimeThread().start();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(AttendaceActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                startLocation();
            } else {
                ActivityCompat.requestPermissions(AttendaceActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            startLocation();
        }
        loadCalendar();
        attendaceListAdapter = new AttendaceListAdapter(AttendaceActivity.this, attendaceBeanList);
        listview.setAdapter(attendaceListAdapter);
        getQuencyCard();
        calendarView.addDecorator(new CustomDecorator());
        calendarView.invalidateDecorators();

    }

    public class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = msgKey;
                    mHandler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case msgKey:
                    long sysTime = System.currentTimeMillis();
                    CharSequence sysTimeStr = DateFormat.format("HH:mm:ss", sysTime);
                    currentTime.setText(sysTimeStr);
                    currentTime1.setText(sysTimeStr);
                    break;
                default:
                    break;
            }
        }
    };




    //初始化calendar
    private void loadCalendar() {
        calendarView.state().edit().setFirstDayOfWeek(Calendar.MONDAY).setMinimumDate(CalendarDay.from(2020, 1, 1)).setMaximumDate(CalendarDay.from(2020, 12, 31))
                .setCalendarDisplayMode(CalendarMode.WEEKS)
                .commit();
        calendarView.setSelectedDate(CalendarDay.today());//当日选中
        calendarView.setSelectionColor(getResources().getColor(R.color.blue_518bfa));//设置选中日期颜色
        calendarView.setTopbarVisible(false);//把顶部左右箭头隐藏掉

        calendarView.setOnDateChangedListener(new OnDateSelectedListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay chooseDate, boolean selected) {
                if (selected) {
                    if (chooseAttendancetype.equals("1")) {
                        int getMonth = chooseDate.getMonth() + 1;
                        if (chooseDate.getMonth()<10&&chooseDate.getDay()<10) {
                            String choosedate = chooseDate.getYear() + ""+"-"+"0"+getMonth +""+"-"+"0"+ chooseDate.getDay();
                            getPunchRecord(choosedate);
                        }else {
                            String todaysdate = chooseDate.getYear() + ""+"-"+getMonth +""+"-"+ chooseDate.getDay();
                            getPunchRecord(todaysdate);
                        }
                    }else {
                        int getMonth = chooseDate.getMonth() + 1;
                        if (chooseDate.getMonth()<10&&chooseDate.getDay()<10) {
                            String choosedate = chooseDate.getYear() + ""+"-"+"0"+getMonth +""+"-"+"0"+ chooseDate.getDay();
                            if (CalendarDay.today().getDay()==chooseDate.getDay()) {
                                fieldLayout.setVisibility(View.VISIBLE);
                                currentAddressLayout.setVisibility(View.VISIBLE);
                                fieldListAdapter = new FieldListAdapter(AttendaceActivity.this, fieldBeanList);
                                listview.setAdapter(fieldListAdapter);
                                FlieldChoosePunch(choosedate);
                            }else {
                                fieldLayout.setVisibility(View.GONE);
                                currentAddressLayout.setVisibility(View.GONE);
                                fieldListAdapters=new FieldListAdapters(AttendaceActivity.this,fieldChooseDateBeanList);
                                listview.setAdapter(fieldListAdapters);
                                FlieldChooseUnTodayPunch(choosedate);
                            }
                        }else {
                            String choosedate = chooseDate.getYear() +""+"-"+ getMonth +""+"-"+ chooseDate.getDay();
                            if (CalendarDay.today().getDay()==chooseDate.getDay()) {
                                fieldLayout.setVisibility(View.VISIBLE);
                                currentAddressLayout.setVisibility(View.VISIBLE);
                                fieldListAdapter = new FieldListAdapter(AttendaceActivity.this, fieldBeanList);
                                listview.setAdapter(fieldListAdapter);
                                FlieldChoosePunch(choosedate);
                            }else {
                                fieldLayout.setVisibility(View.GONE);
                                currentAddressLayout.setVisibility(View.GONE);
                                fieldListAdapters=new FieldListAdapters(AttendaceActivity.this,fieldChooseDateBeanList);
                                listview.setAdapter(fieldListAdapters);
                                FlieldChooseUnTodayPunch(choosedate);
                            }


                        }

                    }

                }
            }
        });
    }

    public class CustomDecorator implements DayViewDecorator {

        Calendar currentTime = Calendar.getInstance();


        @Override
        public boolean shouldDecorate(CalendarDay day) {
            return false;
        }

        @Override
        public void decorate(DayViewFacade view) {



        }
    }


    //开始定位
    private void startLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new bdAbstractLocationListener());
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setPriority(LocationClientOption.GpsFirst);
        option.setCoorType("bd09ll");
        option.setScanSpan(3000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIsNeedAddress(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setWifiCacheTimeOut(6 * 60 * 1000);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }


    @OnClick({R.id.back, R.id.attendace_top_btn, R.id.fieldwork_top_btn, R.id.calendat_pulldown, R.id.calendat_pullup, R.id.attendance_img, R.id.field_img,R.id.field_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (mLocationClient != null) {
                    mLocationClient.stop();
                }
                if (mHandler != null) {
                    mHandler.removeMessages(msgKey);
                }
                finish();
                break;

            case R.id.attendace_top_btn:
                attendaceTopBtn.setBackgroundResource(R.drawable.attendance_shape);
                fieldworkTopBtn.setBackgroundResource(R.drawable.fieldwork_shape);
                attendaceTopBtn.setTextColor(getResources().getColor(R.color.blue_4181fd));
                fieldworkTopBtn.setTextColor(getResources().getColor(R.color.white));
                attendanceLayout.setVisibility(View.VISIBLE);
                fieldLayout.setVisibility(View.GONE);
                attendaceListAdapter = new AttendaceListAdapter(AttendaceActivity.this, attendaceBeanList);
                listview.setAdapter(attendaceListAdapter);
                calendarView.setSelectedDate(CalendarDay.today());//当日选中
                calendarView.setSelectionColor(getResources().getColor(R.color.blue_518bfa));//设置选中日期颜色
                chooseAttendancetype="1";
                getQuencyCard();
                break;

            case R.id.fieldwork_top_btn:
                attendaceTopBtn.setBackgroundResource(R.drawable.attendance_left_shape);
                fieldworkTopBtn.setBackgroundResource(R.drawable.fieldwork_right_shape);
                attendaceTopBtn.setTextColor(getResources().getColor(R.color.white));
                fieldworkTopBtn.setTextColor(getResources().getColor(R.color.blue_4181fd));
                attendanceLayout.setVisibility(View.GONE);
                fieldLayout.setVisibility(View.VISIBLE);
                fieldListAdapter = new FieldListAdapter(AttendaceActivity.this, fieldBeanList);
                listview.setAdapter(fieldListAdapter);
                calendarView.setSelectedDate(CalendarDay.today());//当日选中
                calendarView.setSelectionColor(getResources().getColor(R.color.blue_518bfa));//设置选中日期颜色
                getFelidCard();
                chooseAttendancetype="2";
                currentAddressLayout.setVisibility(View.VISIBLE);
                break;
            case R.id.calendat_pulldown:
                calendatPulldown.setVisibility(View.GONE);
                calendatPullup.setVisibility(View.VISIBLE);
                calendarView.state().edit().setCalendarDisplayMode(CalendarMode.MONTHS).commit();
                break;

            case R.id.calendat_pullup:
                calendatPulldown.setVisibility(View.VISIBLE);
                calendatPullup.setVisibility(View.GONE);
                calendarView.state().edit().setCalendarDisplayMode(CalendarMode.WEEKS).commit();
                break;

            case R.id.attendance_img://上班打卡
                Attendance();
                break;

            case R.id.field_img://外勤打卡
                FlieldPunch();
                break;


            case R.id.field_layout://外勤打卡
                FlieldPunch();
                break;

            default:
                break;
        }
    }

    //判断几次打卡记录
    private void getQuencyCard() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.QUECYCARD, "", new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (attendaceBeanList != null) {
                                    attendaceBeanList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    int counts = 0;
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        AttendaceBean attendaceBean = new AttendaceBean();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        attendaceBean.Id = jsonObject1.optString("Id");
                                        attendaceBean.onehitcard = jsonObject1.optString("onehitcard");
                                        attendaceBean.cixu = jsonObject1.optString("cixu");
                                        attendaceBean.status = jsonObject1.optString("status");
                                        attendaceBean.address = jsonObject1.optString("address");
                                        attendaceBean.type = jsonObject1.optString("type");
                                        attendaceBean.type_one = jsonObject1.optString("type_one");
                                        attendaceBean.status_on = jsonObject1.optString("status_on");
                                        attendaceBeanList.add(attendaceBean);
                                        if (jsonObject1.optString("status_on").equals("0")) {
                                            counts++;
                                        }
                                        if (jsonObject1.optString("status_on").equals("1")) {
                                            break;
                                        }
                                    }
                                    count = counts;
                                    if (attendaceListAdapter != null) {
                                        attendaceListAdapter.refresh(attendaceBeanList);
                                    }
                                    if (count == 1) {
                                        attendenceTxt.setText("下班打卡");
                                    }else  if (count == 2) {
                                        attendenceTxt.setText("上班打卡");
                                    }else  if (count == 3) {
                                        attendenceTxt.setText("下班打卡");
                                    }else if (count == 4) {
                                        attendanceLayout.setVisibility(View.GONE);
                                        currentAddressLayout.setVisibility(View.GONE);
                                    } else {
                                        attendanceLayout.setVisibility(View.VISIBLE);
                                        currentAddressLayout.setVisibility(View.VISIBLE);
                                    }


                                }
                            } else {
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    //TODO
    private void getPunchRecord(String todaysdate) {
        attendanceLayout.setVisibility(View.GONE);
        currentAddressLayout.setVisibility(View.GONE);
        JsonObject jsonObject=new JsonObject();
        jsonObject.addProperty("inputtime",todaysdate);
        OkHttpUtils.getInstance().postWithMemberToken(Url.DAYATTENDACEPUNCH, jsonObject.toString(), new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (attendaceBeanList != null) {
                                    attendaceBeanList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    int counts = 0;
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        AttendaceBean attendaceBean = new AttendaceBean();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        attendaceBean.Id = jsonObject1.optString("Id");
                                        attendaceBean.onehitcard = jsonObject1.optString("onehitcard");
                                        attendaceBean.cixu = jsonObject1.optString("cixu");
                                        attendaceBean.status = jsonObject1.optString("status");
                                        attendaceBean.address = jsonObject1.optString("address");
                                        attendaceBean.type = jsonObject1.optString("type");
                                        attendaceBean.type_one = jsonObject1.optString("type_one");
                                        attendaceBean.status_on = jsonObject1.optString("status_on");
                                        attendaceBeanList.add(attendaceBean);
                                        if (jsonObject1.optString("status_on").equals("0")) {
                                            counts++;
                                        }
                                        if (jsonObject1.optString("status_on").equals("1")) {
                                            break;
                                        }
                                    }
                                    count = counts;
                                    if (attendaceListAdapter != null) {
                                        attendaceListAdapter.refresh(attendaceBeanList);
                                    }
                                    if (count == 4) {
                                        attendanceLayout.setVisibility(View.GONE);
                                        currentAddressLayout.setVisibility(View.GONE);
                                    } else {
                                        attendanceLayout.setVisibility(View.VISIBLE);
                                        currentAddressLayout.setVisibility(View.VISIBLE);
                                    }
                                    listview.setVisibility(View.VISIBLE);

                                }else {
                                    listview.setVisibility(View.GONE);
                                }
                            } else {
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    //判断几次打卡记录
    private void getFelidCard() {
        OkHttpUtils.getInstance().postWithMemberToken(Url.FIELDCARD, "", new OkHttpUtils.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (fieldBeanList != null) {
                                    fieldBeanList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                int flieldcounts = 0;
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        FieldBean fieldBean = new FieldBean();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        fieldBean.Id = jsonObject1.optString("Id");
                                        fieldBean.inputtime = jsonObject1.optString("inputtime");
                                        fieldBean.status = jsonObject1.optInt("status");
                                        fieldBean.address = jsonObject1.optString("address");
                                        fieldBean.status_on = jsonObject1.optString("status_on");
                                        if (jsonObject1.optInt("status")==1) {
                                            fieldBean.lastupdate = 1;
                                        }else {
                                            fieldBean.lastupdate = 2;
                                        }
                                        fieldBeanList.add(fieldBean);
                                    }
                                    for(FieldBean fieldBean : fieldBeanList){
                                        flieldcount= fieldBeanList.get(fieldBeanList.size() - 1).status;

                                    }

                                    if (fieldListAdapter != null) {
                                        fieldListAdapter.refresh(fieldBeanList);
                                    }
                                    fieldImg.setEnabled(true);
                                    if (flieldcount == 1) {
                                        fieldTxt1.setText(getString(R.string.fieldwork_txt));
                                    }else  if (flieldcount == 2) {
                                        fieldTxt1.setText(getString(R.string.fieldworks_txt));
                                    }

                                }
                            } else if (Constant.DATAFAILED.equals(jsonObject.optString("code"))) {
                                fieldImg.setEnabled(true);
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void FlieldChoosePunch(String date) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("inputtime", date);
        OkHttpUtils.getInstance().postWithMemberToken(Url.DAYFIElDACEPUNCH, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (fieldBeanList != null) {
                                    fieldBeanList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        FieldBean fieldBean = new FieldBean();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        fieldBean.Id = jsonObject1.optString("Id");
                                        fieldBean.inputtime = jsonObject1.optString("inputtime");
                                        fieldBean.address = jsonObject1.optString("address");
                                        fieldBean.status_on = jsonObject1.optString("status_on");
                                        fieldBean.status = jsonObject1.optInt("status");
                                        if (jsonObject1.optInt("status")==1) {
                                            fieldBean.lastupdate = 1;
                                        }else {
                                            fieldBean.lastupdate = 2;
                                        }
                                        fieldBeanList.add(fieldBean);
                                    }

                                    if (fieldListAdapter != null) {
                                        fieldListAdapter.refresh(fieldBeanList);
                                    }
                                    fieldImg.setEnabled(true);
                                    listview.setVisibility(View.VISIBLE);


                                    if (flieldcount == 1) {
                                        fieldTxt1.setText(getString(R.string.fieldwork_txt));
                                    }else  if (flieldcount == 2) {
                                        fieldTxt1.setText(getString(R.string.fieldworks_txt));
                                    }
                                }else {
                                    listview.setVisibility(View.GONE);
                                }
                            }  else if (Constant.DATAFAILED.equals(jsonObject.optString("code"))) {
                                fieldImg.setEnabled(true);
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }

    private void FlieldChooseUnTodayPunch(String date) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("inputtime", date);
        OkHttpUtils.getInstance().postWithMemberToken(Url.DAYFIElDACEPUNCH, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                if (fieldChooseDateBeanList != null) {
                                    fieldChooseDateBeanList.clear();
                                }
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        FieldBean fieldBean = new FieldBean();
                                        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
                                        fieldBean.Id = jsonObject1.optString("Id");
                                        fieldBean.inputtime = jsonObject1.optString("inputtime");
                                        fieldBean.address = jsonObject1.optString("address");
                                        fieldBean.status_on = jsonObject1.optString("status_on");
                                        fieldBean.status = jsonObject1.optInt("status");
                                        fieldChooseDateBeanList.add(fieldBean);
                                    }

                                    if (fieldListAdapters != null) {
                                        fieldListAdapters.refresh(fieldChooseDateBeanList);
                                    }
                                    fieldImg.setEnabled(true);
                                    listview.setVisibility(View.VISIBLE);

                                }else {
                                    listview.setVisibility(View.GONE);
                                }
                            }  else if (Constant.DATAFAILED.equals(jsonObject.optString("code"))) {
                                fieldImg.setEnabled(true);
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    //上班打卡
    private void Attendance() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("jinriqi", simpleDateFormat.format(date));
        if (count == 0) {
            jsonObject.addProperty("type", "1");
            jsonObject.addProperty("cixu", "第1次打卡");
            jsonObject.addProperty("status", "上班签到");
        } else if (count == 1) {
            jsonObject.addProperty("type", "3");
            jsonObject.addProperty("cixu", "第2次打卡");
            jsonObject.addProperty("status", "下班签到");
        } else if (count == 2) {
            jsonObject.addProperty("type", "4");
            jsonObject.addProperty("cixu", "第3次打卡");
            jsonObject.addProperty("status", "上班签到");
        } else if (count == 3) {
            jsonObject.addProperty("type", "2");
            jsonObject.addProperty("cixu", "第4次打卡");
            jsonObject.addProperty("status", "下班签到");
        }
        jsonObject.addProperty("address", currentAddress.getText().toString().trim());
        if (latitude == 0.0 && longitude == 0.0) {

        }else {
            jsonObject.addProperty("jingweidu", longitude + "," + latitude);
        }
        OkHttpUtils.getInstance().postWithMemberToken(Url.PUNCHIN, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                ToastUtil.showToast(jsonObject.optString("msg"));
                                getQuencyCard();
                                if (count == 1) {
                                    attendenceTxt.setText("下班打卡");
                                }else  if (count == 2) {
                                    attendenceTxt.setText("上班打卡");
                                }else  if (count == 3) {
                                    attendenceTxt.setText("下班打卡");
                                }else if (count == 4) {
                                    attendanceLayout.setVisibility(View.GONE);
                                    currentAddressLayout.setVisibility(View.GONE);
                                } else {
                                    attendanceLayout.setVisibility(View.VISIBLE);
                                    currentAddressLayout.setVisibility(View.VISIBLE);
                                }

                            } else {
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });

    }


    //外勤打卡
    private void FlieldPunch() {
        pd.setMessage("请稍候");
        pd.show();
        pd.setCanceledOnTouchOutside(false);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = new Date(System.currentTimeMillis());
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("todaysdate", simpleDateFormat.format(date));
        if (latitude == 0.0 && longitude == 0.0) {

        }else {
            jsonObject.addProperty("latitude", longitude + "," + latitude);
        }
        jsonObject.addProperty("address", currentAddress.getText().toString().trim());
        jsonObject.addProperty("inputtime", simpleDateFormat1.format(date1));
        if (flieldcount == 1) {
            jsonObject.addProperty("status",1);
        }else {
            jsonObject.addProperty("status",2);
        }
        OkHttpUtils.getInstance().postWithMemberToken(Url.FIELDPUNCHS, jsonObject.toString(), new OkHttpUtils.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("code"))) {
                                pd.dismiss();
                                ToastUtil.showToast(jsonObject.optString("msg"));
                                getFelidCard();
                            } else {
                                pd.dismiss();
                                ToastUtil.showToast(jsonObject.optString("msg"));
                            }
                        }
                    } catch (JSONException e) {
                        pd.dismiss();
                        e.printStackTrace();
                    }

                } else {
                    pd.dismiss();
                    ToastUtil.showToast(getString(R.string.net_error));
                }
            }
        });
    }


    public class bdAbstractLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            latitude = bdLocation.getLatitude();    //获取纬度信息
            longitude = bdLocation.getLongitude();    //获取经度信息
            currentAddress.setText(bdLocation.getAddrStr());
            if (isFirstLoc) {
                isFirstLoc = false;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mLocationClient != null) {
                mLocationClient.stop();
            }
            if (mHandler != null) {
                mHandler.removeMessages(msgKey);
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        if (mHandler != null) {
            mHandler.removeMessages(msgKey);
        }
        if (pd != null && pd.isShowing()) {
            pd.dismiss();
        }
        if (fieldBeanList != null) {
            fieldBeanList.clear();
        }
        if (fieldChooseDateBeanList != null) {
            fieldChooseDateBeanList.clear();
        }
    }
}
